package org.ymx.myQueue;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author 17122
 */
public class MyQueue<E> implements Iterable<E> {

    private static final int DEFAULT_CAPACITY = 10;

    private E[] items;

    public int size = 0;

    public MyQueue() {
        doClean();
    }

    public MyQueue(int size) {
        this.items = (E[]) new Object[size];
    }

    private void doClean() {
        this.items = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public E get(int index) {
        return items[index];
    }

    public void push(E e) {
        items[this.size] = e;
        this.size++;
    }

    public void remove(int index) {
        if (index <= 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException();
        }
        for (int i = index; i < items.length - 1; i++) {
            items[i] = items[i + 1];
        }
        size--;
    }

    public int size() {
        return size;
    }

    public E poll() {
        E val = items[0];
        remove(0);
        return val;
    }

    public E pop() {
        return items[0];
    }

    @Override
    public Iterator<E> iterator() {
        return new QueueIterator();
    }

    private class QueueIterator implements Iterator<E> {
        @Override
        public boolean hasNext() {
            return pop() != null;
        }

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return pop();
        }
    }
}
